using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameManager : MonoBehaviour
{
   [Header("地图布局数据")]
   public MapLayoutSO mapLayout;
   
   public List<Enemy> aliveEnemyList;
   
   [Header("事件广播")]
   public ObjectEventSO GameWinEvent;
   public ObjectEventSO GameOverEvent;

   /// <summary>
   /// 更新房间的事件监听函数，加载地图
   /// </summary>
   /// <param name="roomVector">房间坐标</param>
   public void UpdateMapDataLayout(object value)
   {
      var roomVector = (Vector2Int) value;
      var room = mapLayout.mapRoomDataList.Find(r => r.column == roomVector.x && r.line == roomVector.y);
      if (mapLayout.mapRoomDataList.Count == 0) return;
      room.roomState = RoomState.Visited;
      //更新相邻房间状态
      var sameColumnRooms = mapLayout.mapRoomDataList.FindAll(r => r.column == roomVector.x);
      foreach (var sameColumnRoom in sameColumnRooms)
      {
         if (sameColumnRoom.line != roomVector.y)
            sameColumnRoom.roomState = RoomState.Locked;
      }
      
      foreach (var link in room.linkTo)
      {
         var linkRoom = mapLayout.mapRoomDataList.Find(r => r.column == link.x && r.line == link.y);
         linkRoom.roomState = RoomState.Attainable;
      }
      
      aliveEnemyList.Clear();
   }

   public void OnLoadRoomEvent(object obj)
   {
      //是否将没有激活的敌人加入到活着的敌人列表，敌人是否排序
      var enemies = FindObjectsByType<Enemy>(FindObjectsInactive.Include, FindObjectsSortMode.None);
      foreach (var enemy in enemies)
      {
         aliveEnemyList.Add(enemy);
      }
   }

   public void OnCharacterDeadEvent(object character)
   {
      if (character is Player)
      {
         //延迟发出失败的通知
         StartCoroutine(EventDelayAction(GameOverEvent));
      }

      if (character is Boss)
         StartCoroutine(EventDelayAction(GameOverEvent));
      else if (character is Enemy)
      {
         //移除死掉的敌人
         aliveEnemyList.Remove(character as Enemy);
         if (aliveEnemyList.Count == 0)
         {
            //延迟发出胜利的通知
            StartCoroutine(EventDelayAction(GameWinEvent));
         }
      }
   }

   IEnumerator EventDelayAction(ObjectEventSO eventSO)
   {
      yield return new WaitForSeconds(2f);
      eventSO.RaisEvent(null,this);
   }

   public void NewGameEvent()
   {
      mapLayout.mapRoomDataList.Clear();
      mapLayout.mapLineData.Clear();
   }
}
